package com.example.nekoneko.service;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.nekoneko.dao.User;
import com.example.nekoneko.mapper.UserMapper;
import com.example.nekoneko.utils.TokenUtils;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import com.example.nekoneko.exception.ServiceException;


@Service
public class UserService extends ServiceImpl<UserMapper, User> {
    @Resource
    UserMapper userMapper;
    @Override
    public boolean save(User entity){
        if (StrUtil.isBlank(entity.getName())) {
            entity.setName(entity.getUsername());
        }
        if (StrUtil.isBlank(entity.getPassword())){
            entity.setPassword("123");//默认为123
        }
        if (StrUtil.isBlank(entity.getRole())){
            entity.setRole("用户");//默认为用户
        }
        return super.save(entity);
    }
    public User selevtByUsername(String username){
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",username);//  eq => ==   where username = #{username}
        //根据用户名查询数据库的用户信息
        return getOne(queryWrapper);//  select * from user where username = #{username}
    }
    //验证用户帐号是否合法
    public User login(User user){
        User dbUser = selevtByUsername(user.getUsername());
        if (dbUser == null){
            //抛出自定义异常
            throw new ServiceException("用户名或密码错误");
        }
        if (!user.getPassword().equals(dbUser.getPassword())){
            throw new ServiceException("用户名或密码错误");
        }
        //生成token
        String token = TokenUtils.createToken(dbUser.getId().toString(),
                dbUser.getPassword());
        dbUser.setToken(token);
        return dbUser;
    }
    public User register(User user){
        User dbUser = selevtByUsername(user.getUsername());
        if (dbUser != null){
            throw new ServiceException("用户已存在");
        }
        user.setName(user.getUsername());
        userMapper.insert(user);
        return user;
    }
    public void resetPassword(User user){
        User dbUser = selevtByUsername(user.getUsername());
        if (dbUser == null){
            throw new ServiceException("用户不存在");
        }
        if (!user.getPhone().equals(dbUser.getPhone())){
            throw new ServiceException("验证错误");
        }
        dbUser.setPassword("123");//重置密码
        updateById(dbUser);
    }
}
